package com.liuzh.kaoyanspringboot.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuzh.kaoyanspringboot.common.Constants;
import com.liuzh.kaoyanspringboot.common.Result;
import com.liuzh.kaoyanspringboot.config.AuthAccess;
import com.liuzh.kaoyanspringboot.controller.dto.UserDTO;
import com.liuzh.kaoyanspringboot.entity.User;
import com.liuzh.kaoyanspringboot.service.UserService;
import com.liuzh.kaoyanspringboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 刘志鸿
 * @since 2023-02-19
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 注册
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        String checkPassword = userDTO.getCheckPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password) || StrUtil.isBlank(checkPassword)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }
        return Result.success(userService.register(userDTO));
    }

    // 登录
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }
        UserDTO dto = userService.login(userDTO);
        return Result.success(dto);
    }

    // 新增或更新
    @PostMapping
    public Result save(@RequestBody User user) {
        return Result.success(userService.saveOrUpdate(user));
//        if (user.getId() != null) {
//            return Result.success( userService.save(user));
//        }
//        return Result.success(userService.updateById(user));
    }


    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody UserDTO userDTO) {
        String password = userDTO.getPassword();
        String username = userDTO.getUsername();
        if (password.equals(userDTO.getCheckPassword())) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",username);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                return Result.error(Constants.CODE_401,"用户不存在");
            }
            if (user.getPassword().equals(userDTO.getOriginPassword())) {
                user.setPassword(password);
                return Result.success(userService.updateById(user));
            } else {
                System.out.println(password + "===========" + user.getPassword());
                return Result.error(Constants.CODE_401,"原密码错误,请从新输入");
            }
        } else {
            System.out.println(password + "===========" + userDTO.getCheckPassword() + "===========" +  userDTO.getOriginPassword());
            return Result.error(Constants.CODE_401,"确认密码与修改密码不一致");
        }
    }

    // 根据 id 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(userService.removeById(id));
    }

    // 批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(userService.removeBatchByIds(ids));
    }

    //查询所有数据
    @GetMapping
    public Result findAll() { return Result.success(userService.list()); }

    // 根据 id 查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }

    // 根据 id 查询
    @AuthAccess
    @GetMapping("/show/{id}")
    public Result findUser(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }

    // 根据 username 查询
    @GetMapping("/username/dto/{username}")
    public Result findOneToUserDTO(@PathVariable String username) {
        if(StrUtil.isBlank(username)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        return Result.success(userService.getbyUsername(username));
    }

    @GetMapping("/username/{username}")
    public Result findOne(@PathVariable String username) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return Result.success(userService.getOne(queryWrapper));
    }

    //简单的分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String username,
                           @RequestParam(defaultValue = "") String nickname,
                           @RequestParam(defaultValue = "") String email,
                           @RequestParam(defaultValue = "") String address) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(!"".equals(username)){
            queryWrapper.like("username",username);
        }
        if(!"".equals(nickname)){
            queryWrapper.like("nickname",nickname);
        }
        if(!"".equals(email)){
            queryWrapper.like("email",email);
        }
        if(!"".equals(address)){
            queryWrapper.like("address",address);
        }
        return Result.success(userService.page(page, queryWrapper));
    }

    //简单的分页查询
//    @GetMapping("/page2")
//    public Result findPage2(@RequestParam Integer pageNum,
//                           @RequestParam Integer pageSize,
//                           @RequestParam(defaultValue = "") String username,
//                           @RequestParam(defaultValue = "") String nickname,
//                           @RequestParam(defaultValue = "") String email,
//                           @RequestParam(defaultValue = "") String address) {
//        Page<User> page = userService.findPage(new Page<>(pageNum, pageSize), username, nickname, email, address);
//        return Result.success();
//    }

    /**
     * 导出接口
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库查出所有的数据
        List<User> list = userService.list();
        //通过工具类创建writer写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUpLoadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("username","用户名");
        writer.addHeaderAlias("password","密码");
        writer.addHeaderAlias("nickname","昵称");
        writer.addHeaderAlias("email","邮箱");
        writer.addHeaderAlias("phone","电话号码");
        writer.addHeaderAlias("address","地址");
        writer.addHeaderAlias("avatarUrl","头像");
        writer.addHeaderAlias("createTime","创建时间");

        //一次性写出list内的对象到Excel, 使用默认样式，强制输出标题
        writer.write(list, true);

        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.speadsheetml.sheet;charset-utf-8");
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        // 通过 response.getOutputStream() 获取输出流， 把writer刷新到out输出流
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * Excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream =file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        /**
         * 正统做法
         * 不用指定
         * @Alias("昵称")
         * private String nickname;
         * 也可以使用
         */
        reader.addHeaderAlias("用户名","username");
        reader.addHeaderAlias("密码","password");
        reader.addHeaderAlias("昵称","nickname");
        reader.addHeaderAlias("邮箱","email");
        reader.addHeaderAlias("电话号码","phone");
        reader.addHeaderAlias("地址","address");
        reader.addHeaderAlias("头像","avatarUrl");
        reader.addHeaderAlias("创建时间","createTime");
        List<User> list = reader.readAll(User.class); //指定类型
//        System.out.println(list);
        return Result.success(userService.saveBatch(list));
    }



}

